/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.service;

import com.rzico.base.BaseMapper;
import com.rzico.base.CommResult;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Supplier;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysUserService;
import com.rzico.exception.CustomException;
import com.rzico.util.CodeGenerator;
import com.rzico.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.basics.mapper.SupplierMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * 供应商业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class SupplierService extends BaseServiceImpl<Supplier, String> {

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Override
    public BaseMapper<Supplier, String> getMapper() {
        return supplierMapper;
    }

    public Supplier findByUserId(String userId) {
        Map<String,Object> params = new HashMap<>();
        params.put("userId",userId);
        List<Supplier> suppliers = selectList(params);
        if (suppliers.size()>0) {
            return suppliers.get(0);
        } else {
            return null;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public Supplier save(Supplier supplier,String password) {
        if (supplier.getUsername()!=null && !"".equals(supplier.getUsername())) {
            SysUser sysUser = new SysUser();
            sysUser.setCreateDate(new Date());
            sysUser.setUsername(supplier.getUsername());
            sysUser.setNickname(supplier.getName());
            sysUser.setDelFlag(false);
            sysUser.setStatus(SysUser.STATUS_ENABLED);
            sysUser.setUserType(1);
            Enterprise enterprise = enterpriseService.findById(supplier.getEnterpriseId());
            sysUser.setMchId(enterprise.getMchId());
            sysUser.setEmail(supplier.getEmail());
            sysUser.setMobile(supplier.getMobile());
            sysUser.setId(CodeGenerator.getUUID());
            sysUser.setPassword(MD5Utils.getMD5Str(password.trim() + sysUser.getUsername().trim()));

            int affectCount = sysUserService.insert(sysUser);
            supplier.setUserId(sysUser.getId());


            if (sysUser!=null) {
                sysUserService.mirror(sysUser, getAuthorization());
            }

        }


        supplierMapper.insertUseGeneratedKeys(supplier);

        return supplier;

    }

}
